package com.hengxinguotong.zhihuichengjian.ui.security;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.AccidentAddPersonAdapter;
import com.hengxinguotong.zhihuichengjian.adapter.AualityTestAddPicAdapter;
import com.hengxinguotong.zhihuichengjian.bean.AddGroupPersonnelListRes;
import com.hengxinguotong.zhihuichengjian.bean.Company;
import com.hengxinguotong.zhihuichengjian.bean.OneCompanyRes;
import com.hengxinguotong.zhihuichengjian.bean.SafetyBean;
import com.hengxinguotong.zhihuichengjian.bean.SafetyRes;
import com.hengxinguotong.zhihuichengjian.bean.Security;
import com.hengxinguotong.zhihuichengjian.bean.Structure;
import com.hengxinguotong.zhihuichengjian.bean.StructureListRes;
import com.hengxinguotong.zhihuichengjian.bean.User;
import com.hengxinguotong.zhihuichengjian.picturebrowser.view.TaskBigImgActivity;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.ui.PersonLiableListActivity;
import com.hengxinguotong.zhihuichengjian.ui.SearchNoticedPersonActivity;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.FileUtil;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.MyStructureTreeView;
import com.hengxinguotong.zhihuichengjian.widget.view.MyTreeView;
import com.hengxinguotong.zhihuichengjian.widget.view.SelectListPop;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * 安全检查
 * Created by Administrator on 2017/10/19.
 */

public class SecurityQuestionActivity extends BaseActivity  implements AualityTestAddPicAdapter.OnRecyclerViewClickListener
{
    @BindView(R.id.tv_title_name)
    HXTextView tvTitleName;
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.save_test)
    HXTextView saveTest;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.date_tv)
    HXTextView dateTv;
    @BindView(R.id.check_date_rl)
    RelativeLayout checkDateRl;
    @BindView(R.id.order_no_tv)
    HXTextView orderNoTv;
    @BindView(R.id.order_no_rl)
    RelativeLayout orderNoRl;
    @BindView(R.id.check_point_tv)
    HXTextView checkPointTv;
    @BindView(R.id.structure_rl)
    RelativeLayout structureRl;
    @BindView(R.id.person_liable_tv)
    HXTextView personLiableTv;
    @BindView(R.id.tel_rl)
    RelativeLayout telRl;
    @BindView(R.id.contacts_moblie_tv)
    HXTextView contactsMoblieTv;
    @BindView(R.id.company_rl)
    RelativeLayout companyRl;
    @BindView(R.id.company_tv)
    HXTextView companyTv;
    @BindView(R.id.team_tv)
    HXTextView teamTv;
    @BindView(R.id.team_rl)
    RelativeLayout teamRl;
    @BindView(R.id.person_number)
    HXTextView personNumber;
    @BindView(R.id.no_notice_tv)
    HXTextView noNoticeTv;
    @BindView(R.id.add_notice_rv)
    RecyclerView addNoticeRv;
    @BindView(R.id.test_project_tv)
    HXTextView testProjectTv;
    @BindView(R.id.result_rl)
    RelativeLayout resultRl;
    @BindView(R.id.select_ll)
    LinearLayout selectLl;
    @BindView(R.id.item_etv)
    HXEditTextView itemEtv;
    @BindView(R.id.result_etv)
    HXEditTextView resultEtv;
    @BindView(R.id.no_pic_tv)
    HXTextView noPicTv;
    @BindView(R.id.add_pic_rv)
    RecyclerView addPicRv;
    @BindView(R.id.complete_time_tv)
    HXTextView completeTimeTv;
    @BindView(R.id.main_sl)
    ScrollView mainSl;
    private AualityTestAddPicAdapter aualityTestAddPicAdapter;
    private List<String> paths;
    private List<String> minPaths;
    private AlertDialog dialog;
    private int year = 0;
    private int monthOfYear = 0;
    private int dayOfMonth = 0;
    private Security security;
    private int type = 3;
    private List<Structure> selectedStructures, leafs;
    private Company company;
    private Company.DataBean group;
    private Handler handler = new Handler();
    private SelectListPop mSelectListPop;
    private User selectUser;
    private List<SafetyBean> selectedDatas, leafDatas;
    //    private List<SafetyBean> selectedFirstDatas;
//    private List<SafetyBean> selectedThirdDatas;
    private List<User> noticedPersons;//告知人员数组
    private AccidentAddPersonAdapter noticedAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type = getIntent().getIntExtra("type", Constants.SECURITY_QUESTION);
        setContentView(R.layout.activity_secury_question);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        security = (Security) getIntent().getSerializableExtra("security");
        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(this);
        linearLayoutManager1.setOrientation(LinearLayoutManager.HORIZONTAL);
        if (security != null) {
            saveTest.setVisibility(View.GONE);
            orderNoRl.setVisibility(View.VISIBLE);
            orderNoTv.setText(security.getOrderNo());
            checkDateRl.setEnabled(false);
            dateTv.setText(security.getBusinessDate());
            Utils.setEditTextViewUnable("", testProjectTv);
            getResultList(security.getId());//获取检查项及结果列表
            Utils.setEditTextViewUnable(security.getResults(), resultEtv);
            Utils.setEditTextViewUnable("", checkPointTv);
            getpProjectStructureList(security.getId());//获取检查部位列表
            if(null != security.getProjectCompanyName()){
                companyRl.setVisibility(View.VISIBLE);
                Utils.setEditTextViewUnable(security.getProjectCompanyName(), companyTv);
            }
            if(null != security.getTeamName()){
                teamRl.setVisibility(View.VISIBLE);
                Utils.setEditTextViewUnable(security.getTeamName(), teamTv);
            }
            Utils.setEditTextViewUnable(security.getContactName(), personLiableTv);
            if(null != security.getContactMobile()){
                telRl.setVisibility(View.VISIBLE);
                Utils.setEditTextViewUnable(security.getContactMobile(), contactsMoblieTv);
            }
            getUserList(security.getId());//获取告知人列表
            Utils.setEditTextViewUnable(security.getCorrectiveCompletionDate(), completeTimeTv);
            if (security.getPicList().size() == 0) {
                noPicTv.setVisibility(View.VISIBLE);
                addPicRv.setVisibility(View.GONE);
            } else {
                addPicRv.setLayoutManager(linearLayoutManager1);
                paths = security.getPicList();
                aualityTestAddPicAdapter = new AualityTestAddPicAdapter(this, paths, this, false);
                addPicRv.setAdapter(aualityTestAddPicAdapter);
            }
        } else {
            orderNoRl.setVisibility(View.GONE);
            Calendar c = Calendar.getInstance();
            year = c.get(Calendar.YEAR);
            monthOfYear = c.get(Calendar.MONTH);
            dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
            dateTv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            completeTimeTv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            addPicRv.setLayoutManager(linearLayoutManager1);
            paths = new ArrayList<String>();
            paths.add(Utils.ADDPIC);
            aualityTestAddPicAdapter = new AualityTestAddPicAdapter(this, paths, this, true);
            addPicRv.setAdapter(aualityTestAddPicAdapter);
            noticedPersons = new ArrayList<User>();
            noticedPersons.add(getAddUser());
            noticedAdapter = new AccidentAddPersonAdapter(this, noticedPersons, new AccidentAddPersonAdapter.OnRecyclerViewClickListener() {
                @Override
                public void onItemClick(View v, int position) {
                    if (Utils.ADDPIC.equals(noticedPersons.get(position).getHeadPortrait())) {
                        Intent intent = new Intent(SecurityQuestionActivity.this, SearchNoticedPersonActivity.class);
                        intent.putExtra("noticedPersons", (Serializable) noticedPersons);
                        startActivityForResult(intent, 5);
                    } else {
                        noticedPersons.remove(position);
                        noticedAdapter.notifyDataSetChanged();
                    }
                }

                @Override
                public void onClick(View v) {

                }
            }, true);
            addNoticeRv.setLayoutManager(getLinearLayoutManager());
            addNoticeRv.setAdapter(noticedAdapter);
            personNumber.setText("已选择" + (noticedPersons.size()-1) + "人");
        }

        if(type == Constants.SECURITY_QUESTION){
            tvTitleName.setText("安全问题");
        }else{
            tvTitleName.setText("日常检查");
        }
    }

    @OnClick({R.id.iv_back, R.id.save_test, R.id.check_date_rl, R.id.check_point_tv, R.id.complete_time_tv, R.id.person_liable_tv,
            R.id.test_project_tv})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.save_test:
                getMinImage();
                break;
            case R.id.check_date_rl:
                showWheelViewDialog();
                break;
            case R.id.check_point_tv:
                intent = new Intent(SecurityQuestionActivity.this, StructureMenuActivity.class);
                intent.putExtra("type", Constants.SECURITY_QUESTION);//1 质量检查界面 2日常安全检查
                startActivity(intent);
                break;
            case R.id.test_project_tv:
                intent = new Intent(SecurityQuestionActivity.this, SafetyCheckItemsActivity.class);
                intent.putExtra("type", Constants.SECURITY_QUESTION);//2施工安全检查 3日常安全检查
                startActivityForResult(intent, 2);
                break;
            case R.id.complete_time_tv:
                showDatePickerDialog();
                break;
            case R.id.company_tv:
                intent = new Intent(SecurityQuestionActivity.this, CompanyListActivity.class);
                CompanyListActivity.FROM = 3;//1 安全检查
                CompanyListActivity.TYPE = 1;//获取公司列表
                startActivity(intent);
                break;
            case R.id.team_tv:
                if (company == null) {
                    return;
                }

                if (company.getData() == null) {
                    return;
                }

                if (company.getData().size() == 0) {
                    return;
                }

                String[] teams = new String[company.getData().size()];
                for (int i = 0; i < company.getData().size(); i++) {
                    teams[i] = company.getData().get(i).getName();
                }
                showSelectPop(teams);
                break;
            case R.id.person_liable_tv:
                intent = new Intent(SecurityQuestionActivity.this, PersonLiableListActivity.class);
                intent.putExtra("type", 0);
                String unableUserId = SPUtil.getString(this, "userId");
                intent.putExtra("unableUserId", unableUserId);
                startActivityForResult(intent, 4);
                break;
        }
    }

    private void getMinImage() {
        if (!checkContent()) {
            return;
        }

        if (paths.size() > 1) {
            Utils.startDownload(getResources().getString(R.string.loading), this);

            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... voids) {
                    minPaths = new ArrayList<String>();
                    for (int i = 0; i < paths.size() - 1; i++) {
                        String path = FileUtil.imageDir1 + System.currentTimeMillis() + ".jpg";
                        FileUtil.writeByteArrayToPath(path, FileUtil.handleUploadImg(paths.get(i)));
                        minPaths.add(path);
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(Void aVoid) {
                    addTest();
                }


            }.execute();
        } else {
            minPaths = new ArrayList<String>();
            addTest();
        }

    }

    private void addTest() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("constructionId", SPUtil.getString(this, "constructionid"));
        for (int i = 0; i < minPaths.size(); i++) {
            params.addBodyParameter("files[" + i + "]", new File(minPaths.get(i)));
        }
        if(type == Constants.SECURITY_QUESTION){
            params.addBodyParameter("type", Constants.DAILY_SECURITY + "");
        }else{
            params.addBodyParameter("type", type + "");
        }
        if(null != leafs && leafs.size() > 0){
            JSONArray jsonArray = new JSONArray();
            try {
                for (int i = 0; i < leafs.size(); i++) {
                    JSONObject object = new JSONObject();
                    object.put("id", leafs.get(i).getId());
                    object.put("name", leafs.get(i).getName());
                    jsonArray.put(object);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            params.addBodyParameter("projectStructureList", jsonArray.toString());
        }
        params.addBodyParameter("contactId", selectUser.getUserId());
        if(selectUser.getMobile() != null){
            params.addBodyParameter("contactMobile", selectUser.getMobile());
        }
        if(selectUser.getProjectCompanyId() != null){
            params.addBodyParameter("projectCompanyId", selectUser.getProjectCompanyId());
        }
        if(selectUser.getTeamId() != null){
            params.addBodyParameter("teamId", selectUser.getTeamId());
        }
        params.addBodyParameter("correctiveCompletionDate", completeTimeTv.getText().toString());
        params.addBodyParameter("inspectDate", year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);

        StringBuffer idSb = new StringBuffer();
        StringBuffer nameSb = new StringBuffer();
        for(int i=0; i<leafDatas.size(); i++){
            if(i == (leafDatas.size()-1)){
                idSb.append(leafDatas.get(i).getId());
                nameSb.append(leafDatas.get(i).getName());
            }else{
                idSb.append(leafDatas.get(i).getId() + ",");
                nameSb.append(leafDatas.get(i).getName() + ",");
            }
        }
        String itemsId = idSb.toString();
        params.addBodyParameter("itemsId", itemsId);
        String items = nameSb.toString();
        if(!Utils.isEmpty(itemEtv.getEditableText().toString())){
            params.addBodyParameter("items", items + "," + itemEtv.getEditableText().toString() + " ");
        }else {
            params.addBodyParameter("items", items );
        }
        params.addBodyParameter("otherItems", itemEtv.getEditableText().toString() + " ");

        if(noticedPersons != null && noticedPersons.size() > 0) {
            JSONArray jsonArray = new JSONArray();
            try {
                for (int i = 1; i < noticedPersons.size(); i++) {
                    JSONObject object = new JSONObject();
                    object.put("userId", noticedPersons.get(i).getUserId());
                    object.put("projectCompanyId", noticedPersons.get(i).getProjectCompanyId());
                    object.put("teamId", noticedPersons.get(i).getTeamId());
                    object.put("mobile", noticedPersons.get(i).getMobile());
                    jsonArray.put(object);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            params.addBodyParameter("userList", jsonArray.toString());
        }
        if(leafDatas != null && leafDatas.size() > 0){
            JSONArray jsonArray = new JSONArray();
            try {
                for(int i=0; i<leafDatas.size(); i++){
                    JSONObject object = new JSONObject();
//                    for(int j=0; j<selectedFirstDatas.size(); j++){
//                        for(int k=0; k<selectedFirstDatas.get(j).getData().size(); k++){
//                            if(selectedFirstDatas.get(j).getData().get(k).getId().equals(selectedThirdDatas.get(i).getParentId())){
//                                object.put("parentItemsId", selectedFirstDatas.get(j).getId());
//                                object.put("parentItemsName", selectedFirstDatas.get(j).getName());
//                            }
//                        }
//                    }
                    object.put("id", leafDatas.get(i).getId());
                    object.put("name", leafDatas.get(i).getName());
                    jsonArray.put(object);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            params.addBodyParameter("resultsList", jsonArray.toString());
            params.addBodyParameter("results", resultEtv.getEditableText().toString());
        }
        params.addBodyParameter("createBy", SPUtil.getString(this, "userId"));
        params.addBodyParameter("processingOpinion", "3");
        Utils.requestData(getResources().getString(R.string.loading), this, "/inspection/constructionSafe/save/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    int status = object.getInt("status");
                    if(status == 0){
                        String msg = object.getString("msg");
                        showToast(msg);
                    }else{
                        showToast("提交成功");
                        setResult(1);
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    @Override
    public void onItemClick(View v, int position) {
        Intent intent;
        if (paths.get(position).equals(Utils.ADDPIC)) {
            List<String> tempStrings = new ArrayList<String>();
            tempStrings.addAll(paths);
            tempStrings.remove(tempStrings.size() - 1);
            MultiImageSelector.create()
                    .showCamera(true) // show camera or not. true by default_grey
                    .count(9) // max select image size, 9 by default_grey. used width #.multi()
                    .multi()
                    .origin((ArrayList<String>) tempStrings)
                    .start(this, 1);
        } else {
            if (security != null) {
                TaskBigImgActivity.startActivity(SecurityQuestionActivity.this, (ArrayList<String>) paths, position);
            } else {
                paths.remove(position);
                aualityTestAddPicAdapter.notifyDataSetChanged();
            }
        }
    }

    private boolean checkContent() {
//        if (structure == null) {
//            showToast("请选择检查部位");
//            return false;
//        }

//        if(company == null){
//            showToast("请选择分包公司");
//            return false;
//        }

//        if(company != null && company.getType() == 2 && company.getData() != null && group == null){
//            showToast("请选择班组");
//            return false;
//        }

        if (year == 0) {
            showToast("请选择日期");
            return false;
        }

        if (type == Constants.SECURITY_QUESTION  && Utils.isEmpty(completeTimeTv.getText().toString())) {
            showToast("请选择整改完成时间");
            return false;
        }

        if(selectUser == null){
            showToast("请选择责任人");
            return false;
        }

        if (leafDatas == null || leafDatas.size() <= 0) {
            showToast("请选择检查项目");
            return false;
        }

        if(Utils.isEmpty(resultEtv.getEditableText().toString())){
            showToast("请填写检查结果");
            return false;
        }
        return true;

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.getSerializableExtra("selectedStructures") != null) {
            selectedStructures = (List<Structure>) intent.getSerializableExtra("selectedStructures");
            leafs = (List<Structure>) intent.getSerializableExtra("leafs");
            processProjectStructure(selectedStructures);
        }

        if(intent.getSerializableExtra("company") != null){
            clearCompany();
            company = (Company) intent.getSerializableExtra("company");
            processCompany(company);
        }

        if(intent.getSerializableExtra("group") != null){
            Company temp = (Company) intent.getSerializableExtra("group");
            processGroup(temp);
        }

        if(intent.getSerializableExtra("selectedDatas") != null){
            selectedDatas = (List<SafetyBean>) intent.getSerializableExtra("selectedDatas");
            processResults(selectedDatas);
        }

        if(intent.getSerializableExtra("leafDatas") != null){
            leafDatas = (List<SafetyBean>) intent.getSerializableExtra("leafDatas");
        }

//        if(intent.getSerializableExtra("selectedThirdDatas") != null){
//            selectedThirdDatas = (List<SafetyBean>) intent.getSerializableExtra("selectedThirdDatas");
//        }
    }

    private void getCompany(String projectStructureId) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("constructionId", SPUtil.getString(this, "constructionid"));
            jsonObject.put("projectStructureId", projectStructureId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(null, this, "/projectCompany/queryDetailByProjectStructionId/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    OneCompanyRes oneCompanyRes = gson.fromJson(json, OneCompanyRes.class);
                    company = oneCompanyRes.getValue();
                    if (company != null) {
                        processCompany(company);
                    }
                }
            }

            @Override
            public void onFailure(String json) {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data != null){
            switch (requestCode){
                case 1:
                    paths = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                    paths.add(Utils.ADDPIC);
                    if (aualityTestAddPicAdapter != null) {
                        aualityTestAddPicAdapter.setPaths(paths);
                    }
                    break;
                case 4:
                    selectUser = new User();
                    selectUser = (User) data.getSerializableExtra("selectUser");
                    processUser(selectUser);
                    break;
                case 5:
                    List<User> temp = (List<User>) data.getSerializableExtra("selectNoticers");
                    for (User user:temp) {
                        if (!user.isInUsers(noticedPersons)) {
                            noticedPersons.add(user);
                        }
                    }
                    noticedAdapter.notifyDataSetChanged();
                    personNumber.setText("已选择" + (noticedPersons.size()-1) + "人");
                    break;
            }
        }
    }

    private void processUser(User user){
        personLiableTv.setText(user.getName());
        if(user.getMobile() != null){
            telRl.setVisibility(View.VISIBLE);
            contactsMoblieTv.setText(user.getMobile());
        }
        if(user.getProjectCompanyId() != null && user.getProjectCompanyName() != null){
            companyRl.setVisibility(View.VISIBLE);
            companyTv.setText(user.getProjectCompanyName());
        }
        if(user.getTeamId() != null && user.getTeamName() != null){
            teamRl.setVisibility(View.VISIBLE);
            teamTv.setText(user.getTeamName());
        }
    }

    private void getpProjectStructureList(String securityId) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("constructionId", SPUtil.getString(this, "constructionid"));
            jsonObject.put("inspectionId", securityId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(null, this, "/inspection/queryInspectionProjectStructure/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    StructureListRes structureListRes = gson.fromJson(json, StructureListRes.class);
                    if(structureListRes.getStatus() == 1){
                        processProjectStructure(structureListRes.getValue());
                    }else{
                        showToast(structureListRes.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String json) {

            }
        });
    }

    private void processProjectStructure(List<Structure> structures){
        MyStructureTreeView mySelectTreeView = new MyStructureTreeView(this);
        mySelectTreeView.setDatas(structures);
        structureRl.removeAllViews();
        structureRl.addView(mySelectTreeView);
    }

    private void getResultList(String securityId) {
        RequestParams params = new RequestParams();
        params.addBodyParameter("constructionId", SPUtil.getString(this, "constructionid"));
        params.addBodyParameter("type", Constants.DAILY_SECURITY + "");

        Utils.requestData(null, this, "/inspection/constructionSafe/queryResultByInspectionId/" + SPUtil.getString(this, "uuid") + "?id=" + securityId, params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    SafetyRes safetyRes = gson.fromJson(json, SafetyRes.class);
                    if(safetyRes.getStatus() == 1){
                        processResults(safetyRes.getValue());
                    }else{
                        showToast(safetyRes.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String json) {

            }
        });
    }

    private void processResults(List<SafetyBean> resultList){
        if(null == resultList || resultList.size() <= 0){
            selectLl.setVisibility(View.GONE);
            Utils.setEditTextViewUnable(security.getItems(), itemEtv);
        }else{
            MyTreeView myTreeView = new MyTreeView(this);
            myTreeView.setDatas(resultList);
            resultRl.removeAllViews();
            resultRl.addView(myTreeView);

            if(null != security){
                if(Utils.isEmpty(security.getOtherItems())){
                    if(!Utils.isEmpty(security.getItems())){
                        String[] items = security.getItems().split(",");
                        if(items.length <= getLeafCount(resultList)){
                            Utils.setEditTextViewUnable("", itemEtv);
                        }else {
                            String item = items[items.length - 1];
                            Utils.setEditTextViewUnable(item, itemEtv);
                        }
                    }else{
                        Utils.setEditTextViewUnable("", itemEtv);
                    }
                }else{
                    Utils.setEditTextViewUnable(security.getOtherItems(), itemEtv);
                }
            }
        }
    }

    int count = 0;
    private int getLeafCount(List<SafetyBean> leafDatas){
        for (SafetyBean safetyBean:leafDatas){
            if(safetyBean.getData().size() <= 0){
                count++;
            }else{
                getLeafCount(safetyBean.getData());
            }
        }
        return count;
    }

    private void getUserList(String securityId) {

        Utils.requestData(null, this, "/inspection/queryNotifyByInspectionId/" + SPUtil.getString(this, "uuid") + "?id=" + securityId, null, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    AddGroupPersonnelListRes personnelListRes = gson.fromJson(json, AddGroupPersonnelListRes.class);
                    if(personnelListRes.getStatus() == 1){
                        processNoticers(personnelListRes.getValue());
                    }else{
                        showToast(personnelListRes.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String json) {

            }
        });
    }

    private void processNoticers(final List<User> noticers){
        if (noticers.size() == 0) {
            noNoticeTv.setVisibility(View.VISIBLE);
        } else {
            noticedAdapter = new AccidentAddPersonAdapter(this, noticers, new AccidentAddPersonAdapter.OnRecyclerViewClickListener() {
                @Override
                public void onItemClick(View v, int position) {
//                    Intent intent = new Intent(DailySecurityTestActivity.this, AddPersonnelActivity.class);
//                    intent.putExtra("type", AddPersonnelActivity.MODTYPE);
//                    intent.putExtra("personId", noticers.get(position).getPersonId());
//                    startActivity(intent);
                }

                @Override
                public void onClick(View v) {

                }
            }, false);
            addNoticeRv.setLayoutManager(getLinearLayoutManager());
            addNoticeRv.setAdapter(noticedAdapter);
            personNumber.setText("已选择" + noticers.size() + "人");
        }
    }
    private LinearLayoutManager getLinearLayoutManager() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        return linearLayoutManager;
    }

    private void processCompany(Company company){
        companyTv.setText(company.getName());
        if(null != company.getData() && company.getData().size() > 0){
            group = company.getData().get(0);
            if(company.getType() == 1){
                teamRl.setVisibility(View.GONE);
            }else if(company.getType() == 2){
                teamRl.setVisibility(View.VISIBLE);
//                teamTv.setText(company.getData().get(0).getName());
            }
//            contactsTv.setText(group.getUserName());
//            contactsMoblieTv.setText(group.getMobile());
        }
    }

    private void processGroup(Company company){
        if(null != company){
            group = new Company.DataBean();
            group.setId(company.getId());
            group.setName(company.getName());
            group.setCompanyId(company.getProjectCompanyId());
            group.setMobile(company.getMobile());
            group.setUserId(company.getUserId());
            group.setUserName(company.getUserName());
            teamTv.setText(company.getName());
            personLiableTv.setText(company.getUserName());
            contactsMoblieTv.setText(company.getMobile());
        }
    }

    private void clearCompany() {
        company = null;
        companyTv.setText("");
        teamTv.setText("");
        personLiableTv.setText("");
        contactsMoblieTv.setText("");
    }

    private User getAddUser() {
        User addUser = new User();
        addUser.setHeadPortrait(Utils.ADDPIC);
        addUser.setUserId("-1");
        addUser.setName("");
        return addUser;
    }

    private void showWheelViewDialog() {
        new DatePickerDialog(this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        SecurityQuestionActivity.this.year = year;
                        SecurityQuestionActivity.this.monthOfYear = monthOfYear;
                        SecurityQuestionActivity.this.dayOfMonth = dayOfMonth;
                        dateTv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                    }
                },
                year, monthOfYear, dayOfMonth).show();
    }

    private void showDatePickerDialog() {
        Calendar c = Calendar.getInstance();
        new DatePickerDialog(this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        completeTimeTv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                    }
                },
                c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)).show();
    }

    private void showSelectPop(final String[] strings) {
        mSelectListPop = new SelectListPop(this, R.layout.dialog_select_sex, strings, new SelectListPop.OnDirListPopItemClicked() {
            @Override
            public void onPopItemClick(int position, String name) {
                group = company.getData().get(position);
                teamTv.setText(group.getName());
                personLiableTv.setText(group.getUserName());
                contactsMoblieTv.setText(group.getMobile());

            }
        });
        mSelectListPop.setFocusable(true);
        mSelectListPop.setOutsideTouchable(true);
        mSelectListPop.setBackgroundDrawable(getResources().getDrawable(R.color.color_transparent));
        mSelectListPop.update();
        mSelectListPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
        if (mSelectListPop.isShowing()) {
            mSelectListPop.dismiss();
        } else {
            mSelectListPop.showAtLocation(mainSl, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
        }
    }

}
